package com.swak.frame.server;

import java.util.concurrent.TimeUnit;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.swak.frame.aware.MonitorAware;
import com.swak.frame.timer.CycleTask;
import com.swak.frame.timer.WheelTimerHolder;

public class ServerHeatbeartMonitor implements MonitorAware {
    private Logger logger = LoggerFactory.getLogger(getClass()); // 日志记录

    private boolean enabled;

    private ServerRegisterService serverRegisterService;

    @Override
    public void startup() {
        logger.warn("ServerRegisterService 启动监控- running>>>>>>>>>>>>>>>>>>>>>>>>>>");
        ServerHeatbeartTask heatbeart = new ServerHeatbeartTask(
            serverRegisterService.getServerconfig().getHeatDelay(), TimeUnit.MINUTES, true, true);
        ServerHeatbeartTask serverStateCheck =
            new ServerHeatbeartTask(1L, TimeUnit.MINUTES, true, false);
        WheelTimerHolder.monitorWheel().newTimeout(serverStateCheck, 90L, TimeUnit.SECONDS);
        WheelTimerHolder.monitorWheel().newTimeout(heatbeart, 60L, TimeUnit.SECONDS);
    }

    class HeatbeartTimerTask extends CycleTask {
        public HeatbeartTimerTask(Long tick, TimeUnit timeUnit, boolean runJob) {
            super.config(tick, timeUnit, runJob);
        }

        @Override
        protected void invoke() {
            logger.info("ServerRegisterService 心跳启动监控-heatbeart running>>>>>>>>>>>>>>>>>>>>>>>>>>");
            serverRegisterService.heatbeart();
        }
    }

    class ServerHeatbeartTask extends CycleTask {
        private boolean heatbeart;

        public ServerHeatbeartTask(Long tick, TimeUnit timeUnit, boolean runJob,
            boolean heatbeart) {
            super.config(tick, timeUnit, runJob);
            this.heatbeart = heatbeart;
        }

        @Override
        protected void invoke() {
            logger.info("ServerRegisterService 心跳启动监控-heatbeart running>>>>>>>>>>>>>>>>>>>>>>>>>>");
            if (heatbeart) {
                serverRegisterService.heatbeart();
            } else {
                serverRegisterService.serverRegister();
            }
        }
    }

    @Override
    public boolean enabled() {
        return this.enabled;
    }

    public void setEnabled(boolean enabled) {
        this.enabled = enabled;
    }

    public void setServerRegisterService(ServerRegisterService serverRegisterService) {
        this.serverRegisterService = serverRegisterService;
    }
}
